package com.sekill.miaosha.controller;


import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.AMQP;
import com.seckill.common.core.domain.R;
import com.seckill.system.api.RemoteGoodsService;
import com.seckill.system.api.RemoteOrderService;
import com.seckill.system.api.RemoteTbUserService;
import com.seckill.system.api.RemoteUserService;
import com.seckill.system.api.domain.TbSku;
import com.seckill.system.api.domain.TbUser;
import com.sekill.miaosha.entity.Stockdto;
import com.sekill.miaosha.entity.TbStock;
import com.sekill.miaosha.mq.MQConfig;
import com.sekill.miaosha.mq.MQSender;
import com.sekill.miaosha.mq.SeckillMessage;
import com.sekill.miaosha.redis.UserKey;
import com.sekill.miaosha.result.CodeMsg;
import com.sekill.miaosha.service.ITbStockService;
import com.sekill.miaosha.utils.CookieUtil;
import com.sekill.miaosha.utils.IdWorker;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 库存表，代表库存，秒杀库存等信息 前端控制器
 * </p>
 *
 * @author gao
 * @since 2021-06-18
 */
@CrossOrigin
@RestController
@RequestMapping("/tb-stock")
@Slf4j
public class TbStockController {

    private static final String prefix = "stock";

    @Autowired
    ITbStockService iTbStockService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RemoteGoodsService remoteGoodsService;

    @Autowired
    RemoteTbUserService remoteTbUserService;

    @Autowired
    MQSender mqSender;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RemoteOrderService remoteOrderService;

    private HashMap<Long,Boolean> localOverMap=new HashMap<Long,Boolean>();

    /*
    *
    *
    */
    public void  afterPropertiesSet(){
        List<TbSku> listgoods = remoteGoodsService.listgoods();
    
        if(listgoods==null){
            return;
        }
        for (TbSku listgood : listgoods) {

            localOverMap.put(listgood.getId(),false);
        }


    }

    @RequestMapping("/seckill2")
    public String list2(Model model,
                        @RequestParam("skuid")Long skuid, HttpServletRequest request) {

        TbStock tbStock = iTbStockService.findbyskuid(skuid);
        Integer stock = tbStock.getStock();
        if(stock<=0){
            model.addAttribute("errmsg", CodeMsg.MIAO_SHA_OVER.getMsg());
            return "miaosha_fail";
        }

        return "order_detail";
    }


    @GetMapping("/seckill")
    @ResponseBody
    public String savetbstock(Model model,
                         @RequestParam("skuId") Long skuId,
                         @RequestParam("token") String token,
                         @RequestParam("seckillPrice") String seckillPrice,
                         HttpServletRequest request){



        System.err.println(skuId+""+token+""+seckillPrice);
        Long userId = remoteTbUserService.getUserId(token);
        System.err.println(userId);
        /*TbStock tbStock = iTbStockService.findbyskuid(skuId);
        Integer stock = tbStock.getStock();
        if(stock<=0){
            return R.ok("库存不足");
        }*/

        boolean findbyuseridandskuid = remoteOrderService.findbyuseridandskuid(skuId, userId);
        if(findbyuseridandskuid==false){
            return "同一个用户只能秒杀本次一次";
        }

        //内存标记，减少redisSeckillMessage访问
        /*Boolean aBoolean = localOverMap.get(skuId);
        if(aBoolean){
            return R.fail(CodeMsg.MIAO_SHA_OVER);
        }*/
        IdWorker idWorker = new IdWorker();
        //预减库存
        Long decrement = redisTemplate.opsForValue().decrement(skuId+"");
        Long orderid=idWorker.nextId();
        System.out.println(orderid);
        redisTemplate.opsForValue().set(orderid+"",1);

        if(decrement<0){
            return "商品库存不足";
        }
        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder().contentEncoding("UTF-8").contentType("text/plain").headers(new HashMap<String, Object>()).priority(0);

        SeckillMessage mm = new SeckillMessage();
        HashMap message = new HashMap();
        message.put("orderid",orderid);
        message.put("userId",userId);
        message.put("skuId",skuId);
        message.put("seckillPrice",new BigDecimal(seckillPrice));

        rabbitTemplate.convertAndSend("queue_work",message);
        log.info("send exchange:{},routingKey:{},message:{}","queue_work", mm);

        return orderid+"";
    }

    @GetMapping("findbyskuid")
    public TbStock findbyskuid(@RequestParam("skuId")Long skuId){
        TbStock findbyskuid = iTbStockService.findbyskuid(skuId);
        System.out.println(findbyskuid);
        return findbyskuid;
    }

    //生成静态页面
    @GetMapping("sendStaticPage")
    public boolean sendStaticPage(@RequestParam("skuId") Long skuId) {
        rabbitTemplate.convertAndSend("queue_work2",skuId);
        return true;
    }

    @GetMapping("getorderid")
    public Object getorderid(@RequestParam("orderId")Long orderId){
        System.err.println(orderId);
        Object o = redisTemplate.opsForValue().get(orderId+"");
        System.err.println(o);
        return o;
    }
}
